package com.dxysun.springboot.wrapper;

import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class MyHttpServletRequestWrapper extends HttpServletRequestWrapper
{
	// 用于存储请求参数
	private Map<String, String> params;

	private Map<String, String> headers = new HashMap<>();

	public MyHttpServletRequestWrapper(HttpServletRequest request)
	{
		super(request);
		Enumeration<String> headerNames = request.getHeaderNames();
		while (headerNames.hasMoreElements())
		{
			String key = headerNames.nextElement();
			headers.put(key, request.getHeader(key));
		}
	}

	public void putHeader(String key, String value)
	{
		headers.put(key, value);
	}

	@Override
	public String getHeader(String name)
	{
		return headers.get(name);
	}

	@Override
	public Enumeration<String> getHeaders(String name)
	{
		return Collections.enumeration(Collections.singletonList(headers.get(name)));
	}

	@Override
	public Enumeration<String> getHeaderNames()
	{
		return Collections.enumeration(headers.keySet());
	}

	/**
	 * 添加参数到map中
	 * @param name
	 * @param value
	 */
	public void setParameter(String name, String value)
	{
		if (params == null)
		{
			params = new HashMap<>();
		}
		params.put(name, value);
	}

	/**
	 * 重写getParameter，代表参数从当前类中的map获取
	 * @param name
	 * @return
	 */
	@Override
	public String getParameter(String name)
	{
		if (params == null)
		{
			return super.getParameter(name);
		}
		String values = params.get(name);
		if (values == null)
		{
			return super.getParameter(name);
		}
		return values;
	}

}
